package java_thinking.unit_21._21_8;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Desc:   8-7 定制 Thread 基类
 *          1.为线程指定名字；
 *          2.设置自定义 UncaughtExceptionHandler 向 Logger 中写入信息；
 *          3.维护一些统计信息(有多少线程被创建和销毁)
 *          4.线程创建或终止时把调试消息写入日志
 * @author: cww
 * @DateTime: 2019/6/17 20:31
 */

public class MyAppThread extends Thread{
    public static final String DEFAULT_NAME = "MyAppThread";
    public static volatile boolean debugLifecycle = false;
    public static final AtomicInteger created = new AtomicInteger();
    private static final AtomicInteger alive = new AtomicInteger();
    private static final Logger log  = Logger.getAnonymousLogger();

    public MyAppThread(Runnable r) {
        this(r, DEFAULT_NAME);
    }

    public MyAppThread(Runnable r, String name) {
        super(r, name + "-" + created.incrementAndGet());
        setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                log.log(Level.SEVERE, "UNCAUGHT in thread " + t.getName(), e);
            }
        });
    }

    @Override
    public void run() {
        //复制 debug 标志以确保一致的值
        boolean debug = debugLifecycle;
        if (debug) log.log(Level.FINE, "Created " +getName());
        try {
            alive.incrementAndGet();
            super.run();
        } finally {
            alive.decrementAndGet();
            if (debug) log.log(Level.FINE, "Exiting " +getName());

        }
    }

    public static int getThreadsCreated() {
        return created.get();
    }

    public static int getThreadsAlive() {
        return alive.get();
    }

    public static boolean getDebug() {
        return debugLifecycle;
    }

    public static void setDebug(boolean b) {
        debugLifecycle = b;
    }
}
